﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Threading;
using System.Globalization;
using System.Net;
using System.IO;

namespace PhotoOfTheDay.Types
{
    public static class Global
    {
        public static Bitmap CurrentImage = null;
        public static bool PhotoFound = false;
        public static bool IsCopyrighted = false;
        public static Config CurrentConfig = default(Config);
        public static Photo CurrentPhoto = default(Photo);

        public static bool IsAuto = false;

        //Set by the update checker
        public static bool UpdateAvailable = false;
        //Url to download the update
        public static string UpdateURL = "";
        //Url to check the update from (bt takes DateTime.Ticks)
        public static string UpdateChackerURL = "http://onuprova.com/pod-changer-check.aspx?bt=";
        public static string OnuprovaPage = "http://onuprova.com";
        public static string FacebookPage = "https://www.facebook.com/pod.wallpaper.changer";

        public static Thread Worker; //Background thread
        public static Thread PhotoArchiver; //Background thread to download photos
        public static Thread Navigator;

        //Wallpaper path used by the PoD changer, in Windows 7 Libraries\Pictures\Photo of the Day\Wallpaper.bmp
        public static string WallpaperPath = "";

        public const string BaseURL = "http://photography.nationalgeographic.com";
        public const string EntranceURL = "http://photography.nationalgeographic.com/photography/photo-of-the-day/";
        public const string ArchiveURL = "http://photography.nationalgeographic.com/photography/photo-of-the-day/archive/?";
        public static string ConfigPath = "Config.bin";
        public static string UpdatePath = "Update.exe";
        public static string UserGuidePath = "National Geographic Photo of the Day Wallpaper Changer v2.0.pdf";
        public static string UserGuideURL = "http://onuprova.com/downloads/National Geographic Photo of the Day Wallpaper Changer v2.0.pdf";
        
        /// <summary>
        /// Reference:http://www.codinghorror.com/blog/2005/04/determining-build-date-the-hard-way.html
        /// </summary>
        /// <returns>Finds linker timestamp from the executable</returns>
        public static DateTime RetrieveLinkerTimestamp()
        {
            string filePath = System.Reflection.Assembly.GetCallingAssembly().Location;
            const int c_PeHeaderOffset = 60;
            const int c_LinkerTimestampOffset = 8;
            byte[] b = new byte[2048];
            System.IO.Stream s = null;

            try
            {
                s = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                s.Read(b, 0, 2048);
            }
            finally
            {
                if (s != null)
                {
                    s.Close();
                }
            }

            int i = System.BitConverter.ToInt32(b, c_PeHeaderOffset);
            int secondsSince1970 = System.BitConverter.ToInt32(b, i + c_LinkerTimestampOffset);
            DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0);
            dt = dt.AddSeconds(secondsSince1970);
            //dont need time zone effect
            //dt = dt.AddHours(TimeZone.CurrentTimeZone.GetUtcOffset(dt).Hours);
            return dt;
        }

        public static bool DownloadFile(string URL, string Path)
        {

            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);
                req.Method = "GET";
                req.Timeout = 10000;
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

                Stream WebStream = resp.GetResponseStream();
                FileStream MyFile = new FileStream(Path, FileMode.Create);
                byte[] buffer = new byte[102400];
                int count = 0;

                while (true)
                {
                    count = WebStream.Read(buffer, 0, buffer.Length);
                    if (count == 0) break;
                    MyFile.Write(buffer, 0, count);
                }
                MyFile.Close();

                resp.Close();
                req.Abort();
            }
            catch
            {
                System.Threading.Thread.Sleep(1000);
                try
                {
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);
                    req.Method = "GET";
                    req.Timeout = 20000;
                    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

                    Stream WebStream = resp.GetResponseStream();
                    FileStream MyFile = new FileStream(Path, FileMode.Create);
                    byte[] buffer = new byte[102400];
                    int count = 0;

                    while (true)
                    {
                        count = WebStream.Read(buffer, 0, buffer.Length);
                        if (count == 0) break;
                        MyFile.Write(buffer, 0, count);
                    }
                    MyFile.Close();

                    resp.Close();
                    req.Abort();
                }
                catch
                {
                    return false;
                }
            }
            return true;
        }

        public static string GetHTTPData(string URL)
        {
            string s = "";
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);
                req.Method = "GET";
                req.Timeout = 10000;
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
                {
                    s = sr.ReadToEnd();
                }
                resp.Close();
                req.Abort();
            }
            catch
            {
                System.Threading.Thread.Sleep(1000);
                try
                {
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);
                    req.Method = "GET";
                    req.Timeout = 20000;
                    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                    using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
                    {
                        s = sr.ReadToEnd();
                    }
                    resp.Close();
                    req.Abort();
                }
                catch
                {
                    return "";
                }
            }
            return s;
        }

        public static string DonationURL = "https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=C2EW8NAF2VWS4&lc=GB&item_name=National%20Geographic%20Photo%20of%20the%20Day%20Wallpaper%20changer&item_number=NGPOD&currency_code=GBP&bn=PP%2dDonationsBF%3abtn_donate_LG%2egif%3aNonHosted";
    
        //Extra windows
        public static Archiver archiver;
    
    }

    public static class Extensions
    {
        public static string ToMonthName(this DateTime dateTime)
        {
            return CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dateTime.Month);
        }
    }

}
